package com.open.capacity.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码生成处
 *
 * @author y022
 */
@Api(tags = "验证码生成")
//@ApiIgnore // 隐藏文档
@Slf4j
@Controller

@RequestMapping("/code")
public class CodeController extends HttpServlet {
    /**
     * 通过java来随机生成验证码
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    @GetMapping("/getCode")
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage img = new BufferedImage(80, 30, BufferedImage.TYPE_INT_ARGB);

        Graphics graphics = img.getGraphics();
        Random random = new Random();

        graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        graphics.fillRect(0, 0, 80, 30);

        //调用自定义的方法，开始自动生产验证码内容(字符串形式)
        String number = getNumber(1);
        req.getSession().setAttribute("code", number);
        System.out.println(number);
        graphics.setColor(new Color(0, 0, 0));
        graphics.setFont(new Font("宋体", Font.BOLD, 24));
        graphics.drawString(number, 5, 25);
        for (int i = 0; i < 5; i++) {
            graphics.setColor(new
                    Color(random.nextInt(255), random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            graphics.drawLine(random.nextInt(100),
                    random.nextInt(30),
                    random.nextInt(100),
                    random.nextInt(30));
//            直线参数 （a,b,x,y),a,b代表起点，x，y代表终点
        }
        resp.setContentType("image/jpeg");
        OutputStream ops = resp.getOutputStream();
        ImageIO.write(img, "jpeg", ops);
        ops.close();
    }

    private String getNumber(int size) {
        String str = "00";
        int length = str.length();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            int le = random.nextInt(length);
            char ss = str.charAt(le);//获得下标所表示的值
            sb.append(ss);
        }
        return sb.toString();
    }
}
